<template>
	<view class="container">
		<u-navbar title="VIP特权" :autoBack="true" :placeholder="true">></u-navbar>
		<view class="content">
			<!-- VIP卡片 -->
			<view class="vip_card" v-if="userInfo">
				<view class="vip_top">
					<image class="vip-icon" src="/static/mine/icon_vip2.png" />
				</view>
				<view class="vip_bottom">
					<image class="vip_avatar" :src="$OssUrl(userInfo.avatar)" mode="aspectFill"></image>
					<text class="vip_expire" v-if="vipInfo">
						<view>有效期至:{{ vipInfo.expiredate }}</view>
						<view style="margin-top: 10rpx;">剩余:{{ vipInfo.remaindays }}天</view>
					</text>
					<text class="vip_expire" v-else>
						<view>暂未开通VIP</view>
					</text>
				</view>
			</view>
			<!-- 套餐说明 -->
			<!-- 价格选项 -->
			<view class="price_options">
				<view :class="selectIndex == index ? 'price_item price_item_active' : 'price_item'"
					v-for="(item, index) in priceList" :key="index" @click="selectIndex = index">
					<view class="item-label" v-if="index == 0">最便宜</view>
					<view class="item-label" v-if="index == 1">最畅销</view>
					<view class="item-label" v-if="index == 2">最省钱</view>
					<text class="price_duration">{{ item.title }}</text>
					<text class="price_value">¥{{ item.price }}</text>
					<text class="price_original">{{ item.subtext }}</text>
				</view>
			</view>
			<!-- 特权标题 -->
			<view class="privilege_title">
				<view class="dot"></view>
				<text class="privilege_text">VIP特权</text>
			</view>
			<!-- 功能列表 -->
			<view class="feature_list">
				<view class="feature_item" v-for="(item, index) in featureList" :key="index">
					<view class="feature_content">
						<view class="feature_icon">
							<image :src="item.image" mode="aspectFill" class="feature_image"></image>
						</view>
						<view class="feature_info">
							<text class="feature_title">{{ item.text }}</text>
							<text class="feature_subtitle">{{ item.intro }}</text>
						</view>
					</view>
					<!-- <u-icon name="arrow-right" size="16" color="#999999" /> -->
				</view>
			</view>
		</view>
		<!-- 底部按钮 -->
		<view class="footer">
			<view class="agreement">
				<text class="agreement-text">支付即代表同意</text>
				<text class="agreement-link"
					@click="$Tips('/pages/richText/richText?biaoshi=value_added_services')">《缘定缘分增值服务协议》</text>
			</view>
			<selectPayType :days="days" :success="getVipInfo" style="width: 90%;margin: 0 auto;"></selectPayType>
		</view>
	</view>
</template>
<script>
// #ifdef H5
import platform from '../../uni_modules/uview-ui/libs/function/platform';
import wxsdk from '@/utils/wechat/sdk.js'
// #endif
import wx from 'weixin-js-sdk';
import selectPayType from '@/components/selectPayType/selectPayType.vue';
// import {
//     Iap,
//     IapTransactionState
//   } from "@/utils/applepay.js"
import request from "@/utils/request.js";
// import { POOL_SUB_ID_SHIT } from 'XrFrame/kanata/lib/kanata';
export default {
	components:{
		selectPayType:selectPayType
	},
	data() {
		return {
			selectIndex: 1,
			pageBg: '/static/common/page_bg2.png',
			avatarUrl: 'https://ai-public.mastergo.com/ai/img_res/9f7b4cfb87096ee6eda93e5cc3cc2b08.jpg',
			vipInfo: null,
			userInfo: null,
			priceList: [],
			featureList: [],
			changePayTypeName: '微信支付',
			_iap:null,
			productList:[],
			productId:'T1',
			loading:false
		}
	},
	onLoad() {
		if(this.isIOS()){
			this.getUserInfo();
			this._iap = new Iap({
			    products: ['T1'] // 苹果开发者中心创建的内购项目 如上面添加的productId：AK10024;['AK10024']
			});
			this.initApplePay();
		}
	},
	computed:{
		days(){
			return this.priceList[this.selectIndex]?.days || '0'
		}
	},
	onShow(options) {
		this.getUserInfo()
		this.getVipInfo()
		if (this._iap?.ready) {
			this.cancelOldOrder();
		}
	},
	methods: {
		isIOS() {
		    const systemInfo = uni.getSystemInfoSync();
		    return systemInfo.platform === 'ios';
		},
		changePayType() {
			if (this.changePayTypeName == '微信支付') {
				this.changePayTypeName = '支付宝支付'
			} else {
				this.changePayTypeName = '微信支付'
			}
		},
		submitVipInfo() {
			//  #ifdef H5
			/*
			this.$Api['user'].submitVipInfo({
				days: this.priceList[this.selectIndex].days,
				paytype: 'wechat',
				method: 'mp'
			}).then(payres => {
				console.log(payres, 'payres')
				wxsdk.wxpay(payres.data, (res) => {
					if (res.errMsg == "chooseWXPay:ok") {
						this.$Toast('支付成功');
						this.getVipInfo()
					} else {
						this.$Toast('支付失败');
					}
				});
			})
			*/
			// #endif
			//  #ifdef APP
			if(this.isIOS()) {
				//调用苹果支付
				this.paymentApple();
				// this.$Api['user'].submitVipInfo({
				// 	days: this.priceList[this.selectIndex].days,
				// 	paytype: 'applepay',
				// 	method: 'app'
				// }).then(payres => {
				// })
			} else {
				if (this.changePayTypeName == '支付宝支付') {
					this.$Api['user'].submitVipInfo({
						days: this.priceList[this.selectIndex].days,
						paytype: 'alipay',
						method: 'app'
					}).then(payres => {
						uni.requestPayment({
							provider: 'alipay',
							orderInfo: payres.data, //微信、支付宝订单数据
							success: (res) => {
								this.$Toast('支付成功');
								this.getVipInfo()
							},
							fail: (err) => {
								this.$Toast('支付失败');
							}
						})
					})
				} else if (this.changePayTypeName == '微信支付') {
					uni.showLoading({
						title:'支付处理中...'
					})
					this.$Api['user'].submitVipInfo({
						days: this.priceList[this.selectIndex].days,
						paytype: 'wechat',
						method: 'app'
					}).then(payres => {
						let params = JSON.parse(payres.data)
						console.log(params,'params');
						uni.requestPayment({
							provider: 'wxpay',
							"orderInfo": {
								"appid": params.appid, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
								"noncestr": params.noncestr, // 随机字符串
								"package": params.package, // 固定值
								"partnerid": params.partnerid, // 微信支付商户号
								"prepayid": params.prepayid, // 统一下单订单号
								"timestamp": params.timestamp, // 时间戳（单位：秒）
								"sign": params.sign // 签名，这里用的 MD5/RSA 签名
							},
							success: (res) => {
								this.$Toast('支付成功');
								this.getVipInfo();
							},
							fail: (err) => {
								console.error('支付失败详情:', err); // 打印完整错误信息
								this.$Toast('支付失败');
							}
						});
					}).finally(()=>{
						uni.hideLoading()
					})
				}
			}
			
			// #endif
		},
		getVipInfo() {
			this.$Api['user'].getVipInfo().then(res => {
				this.vipInfo = res.data.vipInfo
				this.priceList = res.data.vipList.pricedata
				this.featureList = res.data.vipList.rightdata
			})
		},
		getUserInfo() {
			this.$Api['user'].getUserInfo().then(res => {
				this.userInfo = res.data
				console.log("getUserInfo:"+res.data);
			})
		},
		//返回
		navigatorBack() {
			uni.navigateBack({
				delta: 1
			})
		},
		async initApplePay() {
			uni.showLoading({
			  title: '检测支付环境...'
			});	
			try {
			  // 初始化，获取iap支付通道
			  await this._iap.init();
			  // 从苹果服务器获取产品列表
			  this.productList = await this._iap.getProduct();
			  console.log("productId:"+this.productId)
			} catch (e) {
				this.$Toast(e.message);
			} finally {
			  uni.hideLoading();
			}
			if (this._iap._ready) {
			  this.cancelOldOrder();
			}
		},
		async cancelOldOrder() {
			console.log("cancelOldOrder");
		    // 检查上次用户已支付且未关闭的订单，可能出现原因：首次绑卡，网络中断等异常
		    try {
		      // 从苹果服务器检查未关闭的订单，可选根据 username 过滤，和调用支付时透传的值一致
			  let username = this.userInfo.username;
			  console.log("restorePayUser"+username);
		      const transaction = await this._iap.restoreCompletedTransactions({
		        username: username
		      }).then(res => {
				  //关闭未支付的，重新发起
				  res.forEach((trans) => {
					  console.log("cancelPay :" + JSON.stringify(trans));
					  this._iap.finishTransaction(trans);
				  });
			    }).catch(error=>{
					
			    });
		    } catch (e) {
		    } finally {
		    }
		},
		async paymentApple() {
			if (this.loading == true) {
			    return;
			  }
			  this.loading = true;
					
			  uni.showLoading({
			    title: '支付处理中...'
			  });	
			try {
				console.log("this.priceList:"+JSON.stringify(this.priceList));
				this.productList[0].checked = true;
				this.productId = this.productList[0].productid;
			    // 从开发者服务器创建订单
			    // const orderId = await this.createOrder({
			    //   productId: this.productId
			    // });
					
			    // 请求苹果支付
				// 
			   const transaction = await this._iap.requestPayment({
			      productid: this.productId,
			      manualFinishTransaction: true,
			      username: this.userInfo.username //根据业务需求透传参数，关联用户和订单关系
			    }).then(res => {
					console.log("payment");
					this.dealPayResult(res);
				}).catch(error=>{
					this.$Toast('支付失败，请重试');
				});
			    // 支付成功
			} catch (e) {
				this.$Toast(e.message);
			} finally {
			    this.loading = false;
			    uni.hideLoading();
			}
		},
		async dealPayResult(transaction) {
			console.log("dealPayResult:"+transaction.transactionState);
			// 开发者业务逻辑，从服务器获取当前用户未完成的订单列表，和本地的比较
			// 此处省略
			switch (transaction.transactionState) {
			  case IapTransactionState.purchased:
				console.log("zhifuchenggong");
				
			    // 用户已付款，在此处请求开发者服务器，在服务器端请求苹果服务器验证票据
				// 
				let result = await this.validatePaymentResult(transaction);
			    // 验证通过，交易结束，关闭订单
			    // if (result) {
			    //   await this._iap.finishTransaction(transaction);
			    // }
				this.getVipInfo()
			    break;
			  case IapTransactionState.failed:
			    // 关闭未支付的订单
				this.$Toast('支付失败，请重试');
			    break;
			  default:
			    break;
			}
			await this._iap.finishTransaction(transaction);
		},
		async validatePaymentResult(transaction) {
		  let receipt = transaction.transactionReceipt;
		  let order_no = transaction.transactionIdentifier;
		  console.log("发起验证：" + receipt + ";" + order_no);
		 let result = await this.$Api['user'].validatePaymentResult({
		  	receipt: receipt,
		  	order_no: order_no,
		  	method: 'app'
		  }).then(res => {
		  	console.log("ios_verify:"+JSON.stringify(res));
		  }).catch(err => {
		  	console.log("ios_verifyErr:"+JSON.stringify(err));
		  })
		  return result;
		}
	}
}
</script>
<style lang="scss" scoped>
.container {
	width: 100%;
	min-height: 100vh;
	position: relative;
	background-color: #ffffff;
}

.content {
	flex: 1;
	position: relative;
	z-index: 10;
	padding: 40rpx 38rpx 0;
	overflow-y: auto;
	padding-bottom: 240rpx;
	background-image: url('../../static/common/page_bg2.png');
	background-repeat: no-repeat;

}

.vip_card {
	background: url("../../static/mine/vip_bg.png");
	background-size: 100% 100%;
	border-radius: 16rpx;
	padding: 40rpx;
	margin-bottom: 58rpx;
	width: 100%;
	height: 272rpx;
	box-sizing: border-box;

	.vip_top {
		display: flex;
		align-items: center;
		margin-bottom: 74rpx;

		.vip-icon {
			width: 160rpx;
			height: 48rpx;
		}
	}

	.vip_bottom {
		display: flex;
		align-items: center;

		.vip_avatar {
			width: 64rpx;
			height: 64rpx;
			border-radius: 30rpx;
			margin-right: 20rpx;
			border: 2rpx solid #FFFFFF;
		}

		.vip_expire {
			font-size: 28rpx;
			color: #5F3E23;
		}
	}

}




.price_options {
	display: flex;
	justify-content: space-between;
	margin-bottom: 40rpx;
	gap: 20rpx;
}



.price_item {
	flex: 1;
	padding-bottom: 26rpx;
	border-radius: 16rpx;
	text-align: center;
	position: relative;
	background: #FFFFFF;
	box-shadow: 0rpx 0rpx 8rpx 0rpx rgba(241, 105, 246, 0.2);

	.item-label {
		height: 36rpx;
		line-height: 36rpx;
		border-radius: 16rpx 16rpx 0 0;
		font-size: 26rpx;
		color: #FFFFFF;
		text-align: center;
		background: #FEB834;
	}

	&:nth-child(2)::before {
		content: "推荐";
		position: absolute;
		top: -20rpx;
		right: 0;
		background: #FF3E3E;
		border-radius: 13rpx 10rpx 10rpx 0rpx;
		color: #FFFFFF;
		font-size: 18rpx;
		padding: 4rpx 20rpx;
	}
}

.price_item_active {
	background: #FFF9E8;
	border: 2rpx solid #FFCB0A;
	box-shadow: 0rpx 0rpx 8rpx 0rpx rgba(241, 105, 246, 0.2);
}

.price_tag {
	position: absolute;
	top: -20rpx;
	right: 20rpx;
	background-color: #4CAF50;
	color: #FFFFFF;
	font-size: 24rpx;
	padding: 4rpx 12rpx;
	border-radius: 20rpx;
}

.price_tag_hot {
	background-color: #FF69B4;
}

.price_value {
	font-size: 48rpx;
	font-weight: bold;
	color: #333333;
	display: block;
	margin-top: 20rpx;
}

.price_duration {
	font-size: 28rpx;
	color: #666666;
	margin-top: 24rpx;
	display: block;
}

.price_original {
	font-size: 24rpx;
	color: #999999;
	text-decoration: line-through;
	margin-top: 16rpx;
	display: block;
}

.privilege_title {
	display: flex;
	align-items: center;
	margin-bottom: 30rpx;

	.dot {
		width: 12rpx;
		height: 12rpx;
		background: #F169F6;
		box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(241, 105, 246, 0.5);
		border-radius: 8rpx;
		margin-right: 10rpx;
	}

	.privilege_text {
		font-size: 32rpx;
		font-weight: bold;
		margin-left: 10rpx;
	}

}


.feature_list {
	background-color: #FFFFFF;
	border-radius: 16rpx;
}

.feature_item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 26rpx;
	background: #F7F7F7;
	margin-bottom: 20rpx;
	border-radius: 16rpx;

	.feature_content {
		display: flex;
		align-items: center;
	}

	.feature_icon {
		width: 76rpx;
		height: 76rpx;
		margin-right: 20rpx;
	}

	.feature_image {
		width: 100%;
		height: 100%;
		border-radius: 10rpx;
	}

	.feature_info {
		display: flex;
		flex-direction: column;
	}

	.feature_title {
		font-size: 30rpx;
		color: #333333;
		margin-bottom: 6rpx;
	}

	.feature_subtitle {
		font-size: 26rpx;
		color: #9A9A9A;
	}
}

.footer {
	position: fixed;
	z-index: 100;
	width: 100%;
	bottom: 0;
	padding: 30rpx 0;
	background-color: #ffffff;

	.button-group {
		.image {
			width: 38rpx;
			height: 32rpx;
			margin-right: 20rpx;
		}

		.title {
			display: block;
			color: #ffffff;
			text-decoration: none;
		}

		.button1 {
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 0 auto;
			width: 600rpx;
			height: 88rpx;
			font-weight: bold;
			font-size: 30rpx;
			color: #FFFFFF;
			text-align: center;
			line-height: 88rpx;
			background: linear-gradient(135deg, #FE93BF 0%, #A27AFF 100%);
			border-radius: 44rpx;
		}
	}


	.agreement {
		text-align: center;
		margin-bottom: 20rpx;

		.agreement-text {
			font-size: 24rpx;
			color: #999999;
		}

		.agreement-link {
			font-size: 24rpx;
			color: #F169F6;
		}
	}
}
</style>